/**
 * App端文件处理工具
 * 专门为原生App平台优化的文件选择和上传功能
 */

export default {
	/**
	 * App端文件选择
	 * @param {Object} options 选择选项
	 * @returns {Promise} 返回选择的文件列表
	 */
	async chooseFiles(options = {}) {
		const {
			count = 5,
			type = 'file',
			extension = ['txt', 'md', 'html', 'json', 'xml', 'csv', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'rtf']
		} = options;
		
		return new Promise((resolve, reject) => {
			// #ifdef APP-PLUS
			// App端使用plus.io.resolveLocalFileSystemURL
			plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, (fs) => {
				// 使用文档选择器
				plus.nativeUI.actionSheet({
					title: '选择文件来源',
					cancel: '取消',
					buttons: [
						{title: '从相册选择'},
						{title: '从文件管理器选择'},
						{title: '拍照'}
					]
				}, (e) => {
					switch(e.index) {
						case 1: // 相册
							this.chooseFromGallery(count, extension).then(resolve).catch(reject);
							break;
						case 2: // 文件管理器
							this.chooseFromFileManager(count, extension).then(resolve).catch(reject);
							break;
						case 3: // 拍照
							this.chooseFromCamera().then(resolve).catch(reject);
							break;
						default:
							reject(new Error('用户取消选择'));
					}
				});
			}, (error) => {
				console.error('请求文件系统失败:', error);
				reject(error);
			});
			// #endif
			
			// #ifndef APP-PLUS
			// 非App端回退到微信小程序或H5方式
			this.fallbackChooseFiles(options).then(resolve).catch(reject);
			// #endif
		});
	},
	
	/**
	 * 从相册选择图片
	 */
	async chooseFromGallery(count, extension) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: count,
				sizeType: ['original', 'compressed'],
				sourceType: ['album'],
				success: (res) => {
					const files = res.tempFilePaths.map((path, index) => ({
						name: `image_${Date.now()}_${index}.jpg`,
						path: path,
						size: 0, // 图片大小需要另外获取
						type: 'image/jpeg'
					}));
					resolve(files);
				},
				fail: reject
			});
		});
	},
	
	/**
	 * App端文件管理器选择
	 */
	async chooseFromFileManager(count, extension) {
		return new Promise((resolve, reject) => {
			// #ifdef APP-PLUS
			// 使用原生文件选择器
			const Intent = plus.android.importClass('android.content.Intent');
			const Activity = plus.android.runtimeMainActivity();
			
			const intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType('*/*');
			intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, count > 1);
			
			// 设置文件类型过滤
			const mimeTypes = this.getMimeTypes(extension);
			if (mimeTypes.length > 0) {
				intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
			}
			
			Activity.startActivityForResult(intent, 1001);
			
			// 监听Activity结果
			plus.globalEvent.addEventListener('onActivityResult', (result) => {
				if (result.requestCode === 1001) {
					if (result.resultCode === -1) {
						this.handleActivityResult(result.data).then(resolve).catch(reject);
					} else {
						reject(new Error('用户取消选择'));
					}
				}
			});
			// #endif
			
			// #ifndef APP-PLUS
			reject(new Error('当前平台不支持文件管理器选择'));
			// #endif
		});
	},
	
	/**
	 * 拍照选择
	 */
	async chooseFromCamera() {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				sizeType: ['original'],
				sourceType: ['camera'],
				success: (res) => {
					const files = res.tempFilePaths.map((path, index) => ({
						name: `camera_${Date.now()}.jpg`,
						path: path,
						size: 0,
						type: 'image/jpeg'
					}));
					resolve(files);
				},
				fail: reject
			});
		});
	},
	
	/**
	 * 处理Android Activity结果
	 */
	async handleActivityResult(data) {
		// #ifdef APP-PLUS
		return new Promise((resolve, reject) => {
			try {
				const files = [];
				
				if (data.getClipData()) {
					// 多文件选择
					const clipData = data.getClipData();
					for (let i = 0; i < clipData.getItemCount(); i++) {
						const item = clipData.getItemAt(i);
						const uri = item.getUri();
						files.push(this.processFileUri(uri));
					}
				} else if (data.getData()) {
					// 单文件选择
					const uri = data.getData();
					files.push(this.processFileUri(uri));
				}
				
				Promise.all(files).then(resolve).catch(reject);
			} catch (error) {
				reject(error);
			}
		});
		// #endif
	},
	
	/**
	 * 处理文件URI
	 */
	async processFileUri(uri) {
		// #ifdef APP-PLUS
		return new Promise((resolve, reject) => {
			// 获取文件信息
			plus.io.resolveLocalFileSystemURL(uri.toString(), (entry) => {
				entry.file((file) => {
					const reader = new plus.io.FileReader();
					reader.onloadend = () => {
						resolve({
							name: file.name,
							size: file.size,
							type: file.type || 'application/octet-stream',
							path: entry.fullPath,
							data: reader.result
						});
					};
					reader.onerror = reject;
					reader.readAsDataURL(file);
				}, reject);
			}, reject);
		});
		// #endif
	},
	
	/**
	 * 获取MIME类型
	 */
	getMimeTypes(extensions) {
		const mimeMap = {
			'txt': 'text/plain',
			'md': 'text/markdown',
			'html': 'text/html',
			'json': 'application/json',
			'xml': 'application/xml',
			'csv': 'text/csv',
			'pdf': 'application/pdf',
			'doc': 'application/msword',
			'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
			'xls': 'application/vnd.ms-excel',
			'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			'ppt': 'application/vnd.ms-powerpoint',
			'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
			'rtf': 'application/rtf'
		};
		
		return extensions.map(ext => mimeMap[ext]).filter(Boolean);
	},
	
	/**
	 * 非App端回退方案
	 */
	async fallbackChooseFiles(options) {
		const { count, extension } = options;
		
		return new Promise((resolve, reject) => {
			// #ifdef MP-WEIXIN
			// 微信小程序
			uni.chooseMessageFile({
				count: count,
				type: 'file',
				extension: extension,
				success: (res) => {
					const files = res.tempFiles.map(file => ({
						name: file.name,
						size: file.size,
						path: file.path,
						type: file.type || 'application/octet-stream'
					}));
					resolve(files);
				},
				fail: reject
			});
			// #endif
			
			// #ifdef H5
			// H5环境
			const input = document.createElement('input');
			input.type = 'file';
			input.accept = extension.map(ext => `.${ext}`).join(',');
			input.multiple = count > 1;
			input.onchange = (e) => {
				const files = Array.from(e.target.files);
				resolve(files);
			};
			input.click();
			// #endif
		});
	},
	
	/**
	 * 优化的文件上传方法
	 */
	async uploadFiles(files, uploadUrl, formData = {}) {
		const uploadPromises = files.map(file => this.uploadSingleFile(file, uploadUrl, formData));
		return Promise.all(uploadPromises);
	},
	
	/**
	 * 单文件上传
	 */
	async uploadSingleFile(file, uploadUrl, formData = {}) {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: uploadUrl,
				filePath: file.path,
				name: 'file',
				formData: formData,
				success: (res) => {
					try {
						const result = JSON.parse(res.data);
						resolve(result);
					} catch (error) {
						resolve(res.data);
					}
				},
				fail: reject
			});
		});
	}
};
